<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\BaseArea;
use app\common\model\TourRoute;
use app\common\model\TourTemplate;
use app\common\model\TourTemplateDetail;
use ffhome\frame\controller\SimpleCommonController;
use think\db\BaseQuery;

class Template extends SimpleCommonController
{
    protected $modelName = TourTemplate::MODEL_NAME;
    protected $alias = 't';

    protected function getSearchFields(): string
    {
        if (request()->action() == 'routeInfo') {
            return "{$this->alias}.id,{$this->alias}.code,{$this->alias}.name,{$this->alias}.days,{$this->alias}.tags"
                . ",{$this->alias}.pic";
        }
        return "{$this->alias}.id,{$this->alias}.code,{$this->alias}.name,{$this->alias}.days,{$this->alias}.tags"
            . ",{$this->alias}.pic,{$this->alias}.pics,{$this->alias}.feature,{$this->alias}.fee_include"
            . ",{$this->alias}.fee_exclude,{$this->alias}.note,{$this->alias}.status,province.name province_name"
            . ",destination.name city_name," . TourTemplate::getRouteMarketPrice();
    }

    protected function getBaseModel(): BaseQuery
    {
        return parent::getBaseModel()
            ->leftJoin(BaseArea::MODEL_NAME . ' destination', "{$this->alias}.destination_id=destination.id")
            ->leftJoin(BaseArea::MODEL_NAME . ' province', "destination.parent_id=province.id");
    }

    public function map()
    {
        $this->json_result(TourTemplate::getMap());
    }

    public function search()
    {
        $key = request()->param('key', '');
        $this->json_result(TourTemplate::getListByKey($key));
    }

    protected function onAfterDetail(int $id, array &$row)
    {
        $row['pic'] = domainUrl($row['pic']);
        $pics = explode(';', $row['pics']);
        foreach ($pics as &$vo) {
            $vo = domainUrl($vo);
        }
        $row['pics'] = $pics;
        $row['tags'] = explode(';', $row['tags']);
        $row['market_price'] = floatval($row['market_price']);
        $row['details'] = TourTemplateDetail::getListByTemplateId($id);
    }

    public function routeInfo(int $id)
    {
        $row = $this->getModelInfo($id);
        $row['pic'] = domainUrl($row['pic']);
        $row['routes'] = TourRoute::getInfoByTemplateId($id, $row['days']);
        $this->json_result($row);
    }
}